{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "import torch.optim as optim\n",
    "import numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class RMSNorm(torch.nn.Module):\n",
    "    def __init__(self, dim: int, eps: float = 1e-6):\n",
    "        super().__init__()\n",
    "        self.eps = eps\n",
    "        self.weight = nn.Parameter(torch.ones(dim))\n",
    "    def _norm(self, x):\n",
    "        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n",
    "    def forward(self, x):\n",
    "        output = self._norm(x.float()).type_as(x)\n",
    "        return output * self.weight\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 0.9631, -1.3718, -0.0132, -0.1397,  0.4849],\n",
       "         [ 1.9264,  0.1158,  2.1768, -1.6556, -1.1510],\n",
       "         [ 2.0017,  0.7880,  0.0337,  0.2981,  0.4553]],\n",
       "\n",
       "        [[ 3.1775,  0.6852,  0.0552, -0.5085, -0.7955],\n",
       "         [ 0.2360, -0.2756,  0.3686, -1.3898,  2.2636],\n",
       "         [-0.7830, -1.2465, -0.6615,  0.7482,  2.2877]]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_size, seq_len, dim = 2, 3, 5\n",
    "x=torch.randn(batch_size, seq_len, dim)\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dim = 5\n",
    "rmsnorm = RMSNorm(dim)\n",
    "\n",
    "# 创建一个输入张量，形状为 (batch_size, seq_len, dim)\n",
    "batch_size, seq_len, dim = 2, 3, 5\n",
    "x = torch.randn(batch_size, seq_len, dim)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "danwen",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
